package com.zzx.sentinel.controller;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.zzx.sentinel.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: TestController
 * @Description: sentinel测试接口类
 * @Author zhouzhixin
 * @Date 2021/7/19
 * @Version 1.0
 */
@RestController
public class HelloController {

    HelloService helloService;

    @Autowired
    public HelloController(HelloService helloService) {
        this.helloService = helloService;
    }

    @RequestMapping(value = "/hello")
    public String hello() {
        // 调用该接口时初始化一条流控规则到sentinel控制台
        initFlowRule();
        return helloService.hello("test");
    }

    /**
     * <p>初始化流控规则</p>
     *
     * @param
     * @return void
     * @author zhouzhixin
     * @date 2021/7/20 14:12
     */
    public static void initFlowRule() {
        List<FlowRule> rules = new ArrayList<>();
        //定义规则
        FlowRule rule = new FlowRule();
        //定义资源
        rule.setResource("hello");
        //定义模式
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //定义阈值
        rule.setCount(1);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    /**
     * <p>初始化降级规则</p>
     *
     * @param
     * @return void
     * @author zhouzhixin
     * @date 2021/7/20 14:11
     */
    private static void initDegradeRule() {
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource("hello");
        // set threshold rt, 200 ms
        rule.setCount(200);
        // 设置降级规则RT, 平均响应时间
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
        // 设置时间窗口
        rule.setTimeWindow(10);
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }
}

